<?php

namespace app\api\controller\v1;

use app\common\controller\BaseController;
use app\common\service\AlibabaCloudService;
use app\common\service\EasyWechatService;
use think\Cache;
use think\Controller;
use think\Request;

class Sms extends BaseController
{
    /**
     * 发送短信验证码
     */
    public function send()
    {
        $mobile = $this->notEmpty('mobile');
        if (!preg_match('/^1[3,4,5,6,7,8,9][0-9]{9}$/', $mobile)) {
            $this->errorMsg(996);
        }
        //预防恶意刷短信，一天不能超过10次
        $dayTime = strtotime(date('Y-m-d').'23:59:59');
        $count = Cache::get('mobile_count_'.$mobile.date('Ymd'));
        if ($count >= 10) {
            $this->errorMsg(995);
        }
        //验证码
        $templateCode = 'SMS_197945216';
        $code = mt_rand(100000, 999999);
        $params = [
            'code' => $code
        ];
        AlibabaCloudService::sendSms($mobile, $templateCode, $params);
        Cache::set('mobile_code_'.$mobile.$code, $code, 300);
        Cache::set('mobile_count_'.$mobile.date('Ymd'), $count + 1, $dayTime - time());
        $this->success();
    }

    /**
     * 订阅消息
     */
    public function templateList(EasyWechatService $easyWechatService)
    {
        $list = config('wechat.template');
        $this->success('', $list);
    }

    public function test()
    {
        $mobile = '15011996662';
        $templateCode = 'SMS_200175451';
        $params = [
            'name' => 'Chase',
            'datetime' => str_replace('-', '', '2020-08-22').' '.'18:00-22:00'
        ];
        AlibabaCloudService::sendSms($mobile, $templateCode, json_encode($params));
    }
}
